<?php


// 应用公共文件

/**
 * 根据附件表的id返回url地址
 * @param  [type] $id [description]
 * @return [type]     [description]
 */
function geturl($id)
{
    if ($id) {
        $geturl = \think\Db::name("attachment")->where(['id' => $id])->find();
        if ($geturl['status'] == 1) {
            //审核通过
            return $geturl['filepath'];
        } elseif ($geturl['status'] == 0) {
            //待审核
            return '/uploads/xitong/beiyong1.jpg';
        } else {
            //不通过
            return '/uploads/xitong/beiyong2.jpg';
        }
    }
    return false;
}


use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;



function menulist($menu, $id = 0, $level = 0)
{

    static $menus = array();
    foreach ($menu as $value) {
        if ($value['site_pid'] == $id) {
            $value['level'] = $level + 1;
            if ($level == 0) {
                $value['str'] = str_repeat('', $value['level']);
            } elseif ($level == 2) {
                $value['str'] = '&emsp;&emsp;&emsp;&emsp;' . '└ ';
            } elseif ($level == 3) {
                $value['str'] = '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;' . '└ ';
            } else {
                $value['str'] = '&emsp;&emsp;' . '└ ';
            }
            $menus[] = $value;
            menulist($menu, $value['site_id'], $value['level']);
        }
    }
    return $menus;
}

/*
$amount 发送的金额（分）目前发送金额不能少于1元
$re_openid, 发送人的 openid
$desc  //  企业付款描述信息 (必填)
$check_name    收款用户姓名 (选填)
*/
//企业付款到微信零钱，PHP接口调用方法
//define("APPID", "wxde3234454354"); // 商户账号appid
//define("MCHID", "1900000109");        // 商户号
//define("SECRECT_KEY", "145535866885");  //支付密钥签名
function sendMoney($amount, $re_openid, $check_name)
{

    $total_amount = (100) * $amount;
    $data = array(
        'mch_appid' => 'wx33c07abee67996ff',//商户账号appid
        'mchid' => '1518240251',//商户号
        'nonce_str' => createNoncestr(),//随机字符串
        'partner_trade_no' => date('YmdHis') . rand(1000, 9999),//商户订单号
        'openid' => $re_openid,//用户openid
        'check_name' => 'NO_CHECK',//校验用户姓名选项,
        're_user_name' => $check_name,//收款用户姓名
        'amount' => $total_amount,//金额
        'desc' => '健身退款订单',//企业付款描述信息
        'spbill_create_ip' => $_SERVER['SERVER_ADDR'],//Ip地址
    );
    $secrect_key = '0kynui1xn3glzzf10if4wvcv4gjvfspr';///这个就是个API密码。MD5 32位。
    $data = array_filter($data);
    ksort($data);
    $str = '';
    foreach ($data as $k => $v) {
        $str .= $k . '=' . $v . '&';
    }
    $str .= 'key=' . $secrect_key;
    $data['sign'] = md5($str);
    $xml = arraytoxml($data);
    $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'; //调用接口
    $res = curl($xml, $url);
    $return = xmltoarray($res);
    // print_r($return);
    $responseObj = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
//    return $responseObj;
    $res = $responseObj->result_code;  //SUCCESS  如果返回来SUCCESS,则发生成功，处理自己的逻辑
    if($res == 'SUCCESS'){
        return 1;
    }else{
        return $responseObj->err_code_des;
    }
    // $ress = $responseObj->return_code;  //SUCCESS  如果返回来SUCCESS,则发生成功，处理自己的逻辑
    // var_dump($ress);
//    return $res;
}

function curl($param = "", $url)
{

//    return getcwd() . '/cert/1518240251_20181126_cert.pem';
    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();                                      //初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);                 //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        // 终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//    curl_setopt($ch, CURLOPT_SSLCERT, ROOT_PATH . '/wxpay/cacert/apiclient_cert.pem'); //这个是证书的位置绝对路径
//    curl_setopt($ch, CURLOPT_SSLKEY, ROOT_PATH . '/wxpay/cacert/apiclient_key.pem'); //这个也是证书的位置绝对路径
    curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . '/cert/1518240251_20181126_cert.pem'); //这个是证书的位置
    curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . '/cert/1518240251_20181126_key.pem'); //这个也是证书的位置

    $data = curl_exec($ch);                                 //运行curl
    curl_close($ch);
    return $data;
}

function createNoncestr($length = 32)
{

    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";

    $str = "";

    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}


function unicode()
{
    $str = uniqid(mt_rand(), 1);
    $str = sha1($str);
    return md5($str);
}

function arraytoxml($data)
{
    $str = '<xml>';
    foreach ($data as $k => $v) {
        $str .= '<' . $k . '>' . $v . '</' . $k . '>';
    }
    $str .= '</xml>';
    return $str;
}

function xmltoarray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
}




/**
 * 订单号
 */
function number()
{
    $danhao = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $danhao;
}



//随机32位字符串
function nonce_str()
{
    $result = '';
    $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
    for ($i = 0; $i < 32; $i++) {
        $result .= $str[rand(0, 48)];
    }
    return $result;
}


//生成订单号
function order_number($openid)
{
    //date('Ymd',time()).time().rand(10,99);//18位
    return md5($openid . time() . rand(10, 99));//32位
}


//签名 $data要先排好顺序
function sign($data)
{
    $stringA = '';
    foreach ($data as $key => $value) {
        if (!$value) {
            continue;
        }
        if ($stringA) {
            $stringA .= '&' . $key . "=" . $value;
        } else {
            $stringA = $key . "=" . $value;
        }
    }
    $wx_key = '0kynui1xn3glzzf10if4wvcv4gjvfspr';//申请支付后有给予一个商户账号和密码，登陆后自己设置的key
    $stringSignTemp = $stringA . '&key=' . $wx_key;
    return strtoupper(md5($stringSignTemp));
}


//curl请求
function http_request($url, $data = null, $headers = array())
{
    $curl = curl_init();
    if (count($headers) >= 1) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);


    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);


    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}


//获取xml
function xml($xml)
{
    $p = xml_parser_create();
    xml_parse_into_struct($p, $xml, $vals, $index);
    xml_parser_free($p);
    $data = "";
    foreach ($index as $key => $value) {
        if ($key == 'xml' || $key == 'XML') {
            continue;
        }
        $tag = $vals[$value[0]]['tag'];
        $value = $vals[$value[0]]['value'];
        $data[$tag] = $value;
    }
    return $data;
}


//随机数
function GetfourStr($len)
{
    $chars_array = array(
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z",
    );
    $charsLen = count($chars_array) - 1;

    $outputstr = "";
    for ($i = 0; $i < $len; $i++) {
        $outputstr .= $chars_array[mt_rand(0, $charsLen)];
    }
    return $outputstr;
}

//可逆加解密
//$string：字符串，明文或密文；$operation：DECODE表示解密，ENCODE表示加密；$key：密匙；$expiry：密文有效期。
function authcode1($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 0;

    // 密匙
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) :
        substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
    //解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
        sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上并不会增加密文的强度
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}
